package com.xuecheng.content.service.Impl;

import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.service.CourseCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {

    @Autowired
    private CourseCategoryMapper courseCategoryMapper;
    @Override
    public List<CourseCategoryTreeDto> queryCourseCategory(String id) {
        //查询所有课程分类信息
            List<CourseCategoryTreeDto> list = courseCategoryMapper.queryCourseCategory(id);

        ArrayList<CourseCategoryTreeDto> courseCategoryList = new ArrayList<>();
        //把查询到的课程分类信息，封装成需要的格式,.filter(item->!id.equals(item.getId()))目的就是为了把根节点排除
        Map<String,CourseCategoryTreeDto> mapTemp =
        list.stream().filter(item->!id.equals(item.getId())).collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> (key2)));
        //开始遍历，把三级分类全部转化为二级分类的子节点
        list.stream().filter(item->!id.equals(item.getId())).forEach(item->{
            //如果遍历到的节点的父节点为id那么说明该节点是二级节点就加入到list集合中
             if(item.getParentid().equals(id)){
                 courseCategoryList.add(item);
             }
             //找到每个节点的父节点的子节点，如果没空就需要new出来备用
             CourseCategoryTreeDto courseCategoryTreeDto = mapTemp.get(item.getParentid());
             if(courseCategoryTreeDto != null) {
                 if (courseCategoryTreeDto.getChildrenTreeNodes() == null) {
                     courseCategoryTreeDto.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                 }
                 //遍历每一个三级节点，把每一个三级节点放入到二级节点的childrenNode中
                 courseCategoryTreeDto.getChildrenTreeNodes().add(item);
             }
        });
        return courseCategoryList;
    }
}
